package com.yequan.thread.pc.threadpool.blockingqueue;


import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.yequan.thread.threadpool.mythreadpoolmanager.CustomThreadPoolManager;
import com.yequan.thread.threadpool.mythreadpoolmanager.ThreadPoolManagerFactory;

import java.util.concurrent.*;

/**
 * @author : Administrator
 * @date : 2019/11/25
 */
public class ProducerConsumerPattern {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("可用处理器:  "+Runtime.getRuntime().availableProcessors());

        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
        ThreadPoolExecutor executor
                = new ThreadPoolExecutor(4, 8, 2, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000), namedThreadFactory);

        CustomThreadPoolManager cpuIntensiveThreadPoolManager = ThreadPoolManagerFactory.newCpuIntensiveThreadPoolManager();
        CustomThreadPoolManager ioIntensiveThreadPoolManager = ThreadPoolManagerFactory.newIoIntensiveThreadPoolManager();

        Executors.newCachedThreadPool();

        ExecutorService executorService = Executors.newFixedThreadPool(1, namedThreadFactory);
        ExecutorService executorService1 = Executors.newCachedThreadPool(namedThreadFactory);
//        executorService.execute();


        LinkedBlockingQueue queue = new LinkedBlockingQueue(3);
        Consumer myConsumer = new Consumer(queue);
        Producer myProvider = new Producer(queue);
        Consumer myConsumer2 = new Consumer(queue);
        Producer myProvider2 = new Producer(queue);

        for (int i = 0; i < 10; i++) {
            cpuIntensiveThreadPoolManager.addExecuteTask(myProvider);
            cpuIntensiveThreadPoolManager.addExecuteTask(myConsumer);
        }

//        executor.execute(myProvider);
//        executor.execute(myProvider2);
//        executor.execute(myConsumer);
//        executor.execute(myConsumer2);

        myProvider.toStop();
        myConsumer.toStop();

        Thread.sleep(5000);

//        cpuIntensiveThreadPoolManager.shutdown();
//        cpuIntensiveThreadPoolManager = ThreadPoolManagerFactory.newCpuIntensiveThreadPoolManager();

//        for (int i = 0; i < 10; i++) {
//            cpuIntensiveThreadPoolManager.addExecuteTask(myProvider);
//            cpuIntensiveThreadPoolManager.addExecuteTask(myConsumer);
//        }

        while (true) {
            Thread.sleep(1000);
//            int activeCount = executor.getActiveCount();
            int activeCount = cpuIntensiveThreadPoolManager.getActiveCount();
            System.out.println("alive thread count:" + activeCount);
            if (activeCount == 0) {
                System.out.println("executor shutdown");
//                executor.shutdown();
                cpuIntensiveThreadPoolManager.shutdown();
//                break;
                return;
            }
        }
    }
}
